package srcInterviewPrep;

import java.util.ArrayList;
import java.util.List;

public class StringSerializer 
{
    
    private String Normalize(String s)
    {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < s.length(); ++i)
        {
            char c = s.charAt(i);

            if (c == '\\')
            {
                sb.append("\\\\");
            }
            else if (c == ',')
            {
                sb.append("\\,");
            }
            else
            {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    public String Serialize(List<String> strings)
    {
        StringBuilder sb = new StringBuilder();

        for (String s : strings)
        {
            sb.append(Normalize(s));
            sb.append(',');
        }

        return sb.toString();
    }

    public List<String> Deserialize (String serializedString)
    {
        List<String> strings = new ArrayList<String>();
        
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < serializedString.length(); ++i)
        {
            char c = serializedString.charAt(i);

            if (c == '\\')
            {
                if (i + 1 == serializedString.length())
                {
                    throw new RuntimeException(
                    String.format(
                    "Cannot deserialize string '%s'. It contains improper number of \\.",
                    serializedString));
                }

                sb.append(serializedString.charAt(++i));
            }
            else
            {
                if (c == ',')
                {
                    strings.add(sb.toString());
                    sb.setLength(0);
                }
                else
                {
                    sb.append(c);
                }
            }
        }
        
        return strings;
    }    

}
